<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/24
 * Time: 12:01
 */

namespace app\adminapi\controller;

/**
 * @name【北斗相关】
 * @baseurl【adminapi/Beidou】
 */
use app\adminapi\validate\BeidouValidate;
use think\Db;

class Beidou extends Base
{
    public function getRedisData()
    {
        $prefix = '*beidou*';
        $ret = $this->redis->keys($prefix);
        if (empty($ret)) {
            return $this->retError(123);
        }
        $brr = [];
        $nowTime = time();
        foreach ($ret as $v) {
            $arr = $this->redis->get($v);
            $arr = json_decode($arr, true);
            $arr['time'] - $nowTime > 15 * 60 && $arr['alarm'] = '终端没电';
            $arr['time'] - $nowTime > 15 * 60 && $arr['state'] = ' 停止 离线 不定位';
            $brr[] = $arr;
        }
        return $brr;
    }

    public function getRedisBeidou()
    {
        $data = [];
        $data['data'] = $this->getRedisData();
        return $this->retSucc($data);
    }

    public function setCarState()
    {
        $cars = $this->getRedisBeidou();
        $busy = [];
        if ($cars) {
            foreach ($cars AS $car) {
                $car['time'] > time() - 600 && $busy[] = $car['carno'];
            }
        }
        halt($busy);
    }

    /**
     * @name【北斗车辆列表】
     * @desc【北斗车辆列表】
     * @uri【getCars】
     * @method【get/post】
     * @param【
     * token $ string $ abc $ token $ 1 #
     * company_id $ int $ 110 $ 公司id #
     * car_number $ string $ 闽CA123 $ 车牌
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息
     * 】
     */
    public function getCars()
    {
        $validate = new BeidouValidate();
        $whereData = $validate->goCheck()->getCurrentData();
        $cars = $this->getRedisData();
        if (!$cars) {
            return $this->retError('数据请求异常，请重新发起请求。');
        }
        $numbers = array_column($cars, null, 'carno');
        $data = [];
        if(isset($whereData['company_id'])){
            $whereData['entrust_company_id|company_id'] = $whereData['company_id'];
            unset($whereData['company_id']);
        }
        $list = Db::name('car')->field('car_id,number,entrust_company_id,company_id')->whereNull('delete_time')->where($whereData)->select();
        foreach ($list AS $id => $value) {
            $beidou = $numbers[$value['number']];
            $value['loc'] = [$beidou['lon'], $beidou['lat']];
            $states = explode(' ', trim($beidou['state']));
            switch ($states[0]) {
                case '停止':
                    $value['state'] = 1;
                    break;
                case '行驶':
                    $value['state'] = 2;
                    break;
                case '':
                    $value['state'] = 4;
                    break;
            }
            if ($states[1] == '离线') $value['state'] = 3;
            $value['alarm'] = $beidou['alarm'];
            $value['time'] = date('Y-m-d H:i', $beidou['time']);
            $data[$id] = $value;
        }
        return $this->retSucc(['data' => $data]);
    }

    /**
     * @name【获取北斗轨迹】
     * @desc【】
     * @method【get】
     * @param【
     *    oid $ int $ 1000 $ 订单ID $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function getTrack()
    {
        $oid = input('oid', 0);
        return (new \app\api\model\Order())->getTrack($oid);
    }

    /**
     * @name【获取所有北斗车辆】
     * @desc【】
     * @method【get】
     * @param【
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */

    public function cars()
    {

        $state = input('param.state');
        $cars = $this->getRedisData();

        if ($cars) {
//			
            #$data = array_column($cars,null,'driver_id');
            $numbers = array_column($cars, null, 'carno');
            #$ids = array_column($json['data'],'carno');
            //
            $where = $data = [];
            $where['is_beidou'] = 1;
            $number = input('param.number', '', 'urldecode');
            $car_rental_id = input('param.car_rental_id');
            $number && $where['number'] = ['like', "%{$number}%"];
            $car_rental_id && $where['car_rental_id'] = ['like', "%{$car_rental_id}%"];

            //数据库
            #$list = Db::name('car')->alias('c')->join('driver m','m.car_id = c.car_id','left')->field('m.driver_id,c.car_id,m.name,c.number,m.phone,m.work_state')->where($where)->select();
            $list = Db::name('car')->field('car_id,number')->where($where)->select();

            foreach ($list AS $id => $value) {

                $beidou = $numbers[$value['number']];
                $value['loc'] = [$beidou['lon'], $beidou['lat']];
                $states = explode(' ', trim($beidou['state']));
                switch ($states[0]) {
                    case '停止':
                        $value['state'] = 1;
                        break;
                    case '行驶':
                        $value['state'] = 2;
                        break;
                    case '':
                        $value['state'] = 4;
                        break;
                }
                //离线
                if ($states[1] == '离线') $value['state'] = 3;
                //预警
                $value['alarm'] = $beidou['alarm'];
                $value['time'] = date('Y-m-d H:i', $beidou['time']);

                $data[$id] = $value;

            }

//			halt($list);
            return $this->success('数据请求成功。', '', $data);

        } else {
            return $this->error('数据请求异常，请重新发起请求。');
        }
    }

    /**
     * @name【获取北斗异常】
     * @desc【】
     * @uri【getException】
     * @method【get】
     * @param【
     *    page $ int $ 1 $ 页码 $ 0 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function getException()
    {

        $cars = $this->getRedisData();

        foreach ($cars AS $car) {
            if ($car['alarm']) {
                $car['datetime'] = date('Y-m-d H:i', $car['time']);
                $data[] = $car;
            }
        }

        $count = count($data);
        //分页
        $page = input('param.page', 1);
        $offset = ($page - 1) * 10;

        $data = array_slice($data, $offset, 10);
        $data = ['count' => $count, 'list' => $data];

        return $this->retAll($data);
    }

    /**
     * @name【获取当前位置】
     * @desc【】
     * @uri【getCurrentLoc】
     * @method【get】
     * @param【
     *  car_number $ string $ 闽C88888 $ 车牌 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */

    public function getCurrentLoc()
    {

        $car_number = input('param.car_number');

//		$json = file_get_contents('http://new.jjcxfw.com/api/driver.index/getredisbeidou');
//		$json = json_decode($json,1);
        $cars = $this->getRedisData();
        $data = array_column($cars, null, 'carno');

        return $this->apiout($data[$car_number]);

    }

    /**
     * @name【获取订单】
     * @desc【】
     * @uri【orders】
     * @method【get】
     * @param【
     *  id $ int $  1000 $ 订单ＩＤ $ 1 #
     *  page $ int $ 1 $ 页数 $ 1 #
     *  pagesize $ int $ 10 $ 每页显示数量 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function orders()
    {

        $id = input('param.id/d');
        $page = input('param.page/d', 1);
        $size = input('param.pagesize/d', 10);

        $list = Db::name('order')->alias('o')
            ->join('order_fee of', 'of.order_id = o.order_id')
            ->join('order_gps og', 'og.order_id = o.order_id')
            ->join('driver d', 'd.driver_id = o.driver_id')
            ->where('o.car_id', $id)->field('o.*,d.name AS driver_name,of.order_money, of.passenger_money,og.from_lon,og.from_lat, og.from_addr AS begin, og.to_addr AS end')->page($page)->limit($size)->order('order_time DESC')->select();

        if ($list) {
            return $this->success('数据请求成功。', '', $list);
        }
        return $this->error('数据请求异常，请重新发起请求。');

    }

    /**
     * @name【获取指定车牌某个时段的北斗轨迹】
     * @desc【】
     * @uri【getDate】
     * @method【get】
     * @param【
     *  act $ int $  ''/'export' $ 是否导出 $ 1 #
     *  number $ int $  1000 $ 车牌 $ 1 #
     *  start $ int $ 1 $ 开始时间 $ 1 #
     *  end $ int $ 10 $ 结束时间 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息#
     * data $ int $  $ 数据 $[{"201801":[],"201802":[],"201803":[],"201804":[]}]
     * 】
     */
    public function getDate()
    {

        $act = input('param.act');

        $number = input('param.number');
        $start = input('param.start');
        $end = input('param.end');

        $md5 = md5($number);
        //时间段
        $starttime = strtotime($start);
        $endtime = strtotime($end);
        $diff = max(0, ($endtime - $starttime) / (24 * 3600), 10);

        $start = date('Y-m-d H:i:s', $starttime);
        $end = date('Y-m-d H:i:s', $endtime);

        $beidou = $lines = $content = [];
        for ($i = 0; $i <= $diff; $i++) {
            $date = date('Ymd', $starttime + $i * 24 * 3600);
            $file = "/work/ucar/beidou/{$md5}/{$date}*.txt";

            $list = glob($file);
            if ($list) {
                foreach ($list AS $file) {
                    $lines = file($file);
                    if ($lines) {
                        foreach ($lines AS $line) {
                            if ($info = explode('|', $line)) {
                                //比较时分秒
                                if ($info[11] >= $start && $info[11] <= $end) {
                                    $beidou[] = [$info[4], $info[5]];

                                    array_push($content, [$number, $info[11], $info[4], $info[5], $info[6], floatval($info[12]), $info[8], $info[9]]);
                                }
                            }
                        }
                    }

                }
            }
        }

        if ($act == 'export') {
            $title = ['车牌号', '时间', '经度', '纬度', '速度', '里程', '相对里程', '车辆状态'];
            return $this->xls($number . '_' . $start . ' ' . $end . ' Beidou', $title, $content);
        } else {
            return $this->apiout($beidou);
        }

    }

}